<?php

use App\Models\AdminUser;
use App\Models\Permission;
use App\Models\Role;
use App\Models\RoleHasPermission;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class AdminUsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->command->info('清空舊數據');
        collect([
            'admins',
            'permissions',
            'roles',
            'role_has_permissions',
            'model_has_roles'
        ])->tap(function ($tables) {
            $this->command->getOutput()->progressStart($tables->count() + 2);
            DB::statement('SET FOREIGN_KEY_CHECKS=0;');
            $this->command->getOutput()->progressAdvance();
        })->each(function ($table) {
            DB::table($table)->truncate();
            $this->command->getOutput()->progressAdvance();
        })->tap(function () {
            DB::statement('SET FOREIGN_KEY_CHECKS=1;');
            $this->command->getOutput()->progressAdvance();
            $this->command->getOutput()->progressFinish();
        });

        $this->command->info('增加權限組、角色、角色關聯權限');
        $this->command->getOutput()->progressStart(3);
        // 增加權限
        $permission = Permission::create([
            'name'       => 'all',
            'guard_name' => 'web',
            'route'      => '*',
        ]);
        $this->command->getOutput()->progressAdvance();
        // 增加角色
        $role = Role::create([
            'name'       => 'administrator',
            'guard_name' => 'web',
        ]);
        $this->command->getOutput()->progressAdvance();
        // 角色關聯權限
        RoleHasPermission::create([
            'permission_id' => $permission->id,
            'role_id'       => $role->id,
        ]);
        $this->command->getOutput()->progressAdvance();
        $this->command->getOutput()->progressFinish();
        // 增加用戶
        collect([
            [
                'staff_id' => '10709',
                'password' => bcrypt('123456'),
                'name'     => 'FC',
                'nickname' => 'FC',
                'roles'    => [
                    [
                        'role_id'    => $role->id,
                        'model_type' => 'App\\Models\\AdminUser',
                    ],
                ],
            ],
        ])->tap(function ($users) {
            $this->command->info('增加用戶');
            $this->command->getOutput()->progressStart($users->count());
        })->each(function ($user) {
            $roles = $user['roles'];
            unset($user['roles']);
            $user = AdminUser::create($user);
            foreach ($roles as &$role) {
                $role['model_id'] = $user->id;
            }
            DB::table('model_has_roles')->insert($roles);
            $this->command->getOutput()->progressAdvance();
        })->tap(function () {
            $this->command->getOutput()->progressFinish();
        });
    }
}
